/*
 * Copyright 2010 Spolecne s.r.o. (www.spoledge.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.api.datastore;


/**
 * This is a GWT emulation class.
 * It is ONLY used on the client side - JavaScript.
 *
 * This class is intended to use with custom DTO serializers
 * generated by AuDAO.
 *
 * This is only used to construct keys.
 */
public class KeyFactory {

    public static final class Builder {

        private Key key;


        public Builder(String kind, String name) {
            key = KeyFactory.createKey(null, kind, name);
        }

        public Builder(String kind, long id) {
            key = KeyFactory.createKey(null, kind, id);
        }

        public Builder(Key key) {
            this.key = key;
        }


        public Builder addChild(String kind, String name) {
            key = KeyFactory.createKey(key, kind, name);
            return this;
        }

        public Builder addChild(String kind, long id) {
            key = KeyFactory.createKey(key, kind, id);
            return this;
        }


        public Key getKey() {
            return key;
        }
    }


    private KeyFactory() {
    }

    public static Key createKey(String kind, long id) {
        return createKey(null, kind, id);
    }

    public static Key createKey(Key parent, String kind, long id) {
        if (id == 0L) throw new IllegalArgumentException("id cannot be zero");
        else return new Key(kind, parent, id, null);
    }

    public static Key createKey(String kind, String name) {
        return createKey(null, kind, name);
    }

    public static Key createKey(Key parent, String kind, String name) {
        if (name == null || name.length() == 0) {
            throw new IllegalArgumentException("name cannot be null or empty");
        }
        else return new Key(kind, parent, 0, name);
    }

}
